<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="村名字">
        <el-select
          v-model="queryParams['bankVillage.villageName']"
          placeholder="请选择村名字"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="item in villageList"
            :key="item.villageId"
            :label="item.villageName"
            :value="item.villageName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="户标签" prop="domicileLabel">
        <el-select v-model="queryParams.domicileLabel" placeholder="请选择户标签" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.bank_domicile_label"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="主信贷人村民编号" prop="domicileVillagerId">
        <el-input
          v-model="queryParams.domicileVillagerId"
          placeholder="请输入主信贷人村民编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bank:domicile:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bank:domicile:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bank:domicile:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bank:domicile:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" v-show="isQuerySet" :data="domicileList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="表序号" align="center" prop="domicileId" />
      <el-table-column label="村名字" align="center" prop="bankVillage.villageName" />

      <el-table-column label="户籍号" align="center" prop="domicileNumber" />
      <el-table-column label="户标签" align="center" prop="domicileLabel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bank_domicile_label" :value="scope.row.domicileLabel"/>
        </template>
      </el-table-column>
      <el-table-column label="主信贷人姓名" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.domicileVillagerId">
            <el-tooltip class="item" effect="dark" :content="getVillagerTooltipContent(scope.row.domicileVillagerId)" placement="top">
              <span>{{ getVillagerName(scope.row.domicileVillagerId) }}</span>
            </el-tooltip>
          </template>
          <template v-else>
            <!-- 如果domicileVillagerId为空，不显示任何内容也不显示悬停提示 -->
          </template>
        </template>
      </el-table-column>
      <el-table-column label="一轮预授信金额" align="center">
        <template slot-scope="scope">
          <template v-if="parseFloat(scope.row.oneMoney) > 0">{{ scope.row.oneMoney }}</template>
        </template>
      </el-table-column>
      <el-table-column label="一轮评议员姓名" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.oneSenatorId">
            <el-tooltip class="item" effect="dark" :content="getSenatorTooltipContent(scope.row.oneSenatorId)" placement="top">
              <span>{{ getSenatorName(scope.row.oneSenatorId) }}</span>
            </el-tooltip>
          </template>
          <template v-else>
            <!-- 如果domicileVillagerId为空，不显示任何内容也不显示悬停提示 -->
          </template>
        </template>
      </el-table-column>
      <el-table-column label="二轮预授信金额" align="center">
        <template slot-scope="scope">
          <template v-if="parseFloat(scope.row.twoMoney) > 0">{{ scope.row.twoMoney }}</template>
        </template>
      </el-table-column>
      <el-table-column label="二轮评议员姓名" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.twoSenatorId">
            <el-tooltip class="item" effect="dark" :content="getSenatorTooltipContent(scope.row.twoSenatorId)" placement="top">
              <span>{{ getSenatorName(scope.row.twoSenatorId) }}</span>
            </el-tooltip>
          </template>
          <template v-else>
            <!-- 如果domicileVillagerId为空，不显示任何内容也不显示悬停提示 -->
          </template>
        </template>
      </el-table-column>
      <el-table-column label="白名单复议预授信金额" align="center">
        <template slot-scope="scope">
          <template v-if="parseFloat(scope.row.whiteMoney) > 0 && scope.row.whiteMoney !== '-1'">{{ scope.row.whiteMoney }}</template>
        </template>
      </el-table-column>
      <el-table-column label="白名单复议评议员姓名" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.whiteSenatorId">
            <el-tooltip class="item" effect="dark" :content="getSenatorTooltipContent(scope.row.whiteSenatorId)" placement="top">
              <span>{{ getSenatorName(scope.row.whiteSenatorId) }}</span>
            </el-tooltip>
          </template>
          <template v-else>
            <!-- 如果domicileVillagerId为空，不显示任何内容也不显示悬停提示 -->
          </template>
        </template>
      </el-table-column>
      <el-table-column label="是否进行品质评议" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.domicileQuality === 'Y'">
            <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.domicileQuality"/>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="品质评议员姓名" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.domicileQualitySenatorId">
            <el-tooltip class="item" effect="dark" :content="getSenatorTooltipContent(scope.row.domicileQualitySenatorId)" placement="top">
              <span>{{ getSenatorName(scope.row.domicileQualitySenatorId) }}</span>
            </el-tooltip>
          </template>
          <template v-else>
            <!-- 如果domicileVillagerId为空，不显示任何内容也不显示悬停提示 -->
          </template>
        </template>
      </el-table-column>
      <el-table-column label="预授信额度" align="center">
        <template slot-scope="scope">
          <template v-if="parseFloat(scope.row.money) > 0">{{ scope.row.money }}</template>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bank:domicile:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bank:domicile:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 在表格上方显示提示信息 -->
    <el-alert
      v-show="!isQuerySet"
      type="info"
      title="提示：请先选择行政村！"
      :closable="false"
    ></el-alert>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改评议情况对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="村名字" prop="villageId">
          <el-select v-model="form.villageId" placeholder="请选择村名字">
            <el-option
              v-for="item in villageList"
              :key="item.villageId"
              :label="item.villageName"
              :value="item.villageId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="户籍号" prop="domicileNumber">
          <el-input v-model="form.domicileNumber" placeholder="请输入户籍号" />
        </el-form-item>
        <el-form-item label="户标签" prop="domicileLabel">
          <el-select v-model="form.domicileLabel" placeholder="请选择户标签">
            <el-option
              v-for="dict in dict.type.bank_domicile_label"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主信贷人村民编号" prop="domicileVillagerId">
          <el-input v-model="form.domicileVillagerId" placeholder="请输入主信贷人村民编号" />
        </el-form-item>
        <el-form-item label="一轮预授信金额" prop="oneMoney">
          <el-input v-model="form.oneMoney" placeholder="请输入一轮预授信金额" />
        </el-form-item>
        <el-form-item label="一轮评议员编号" prop="oneSenatorId">
          <el-input v-model="form.oneSenatorId" placeholder="请输入一轮评议员编号" />
        </el-form-item>
        <el-form-item label="二轮预授信金额" prop="twoMoney">
          <el-input v-model="form.twoMoney" placeholder="请输入二轮预授信金额" />
        </el-form-item>
        <el-form-item label="二轮评议员编号" prop="twoSenatorId">
          <el-input v-model="form.twoSenatorId" placeholder="请输入二轮评议员编号" />
        </el-form-item>
        <el-form-item label="白名单复议预授信金额" prop="whiteMoney">
          <el-input v-model="form.whiteMoney" placeholder="请输入白名单复议预授信金额" />
        </el-form-item>
        <el-form-item label="白名单复议评议员编号" prop="whiteSenatorId">
          <el-input v-model="form.whiteSenatorId" placeholder="请输入白名单复议评议员编号" />
        </el-form-item>
        <el-form-item label="是否进行品质评议" prop="domicileQuality">
          <el-select v-model="form.domicileQuality" placeholder="请选择是否进行品质评议">
            <el-option
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品质评议员编号" prop="domicileQualitySenatorId">
          <el-input v-model="form.domicileQualitySenatorId" placeholder="请输入品质评议员编号" />
        </el-form-item>
        <el-form-item label="预授信额度" prop="money">
          <el-input v-model="form.money" placeholder="请输入预授信额度" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDomicile, getDomicile, delDomicile, addDomicile, updateDomicile } from "@/api/bank/domicile";
import{listVillagers} from "@/api/bank/villagers";
import {listVillage,getVillage} from "@/api/bank/village";
import {listBranch} from "@/api/bank/branch";
import{listSenator} from "@/api/bank/senator";

export default {
  name: "Domicile",
  dicts: ['sys_yes_no', 'bank_domicile_label'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 评议情况表格数据
      domicileList: [],
      // 行政村数据
      villageList:[],
      // 行政村数据
      villagersList:[],
      //评议员数据
      senatorList:[],
      // 弹出层标题
      title: "",
      // 是否设置了查询条件
      isQuerySet: false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        'bankVillage.villageName':null,
        domicileLabel: null,
        domicileVillagerId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        villageId: [
          { required: true, message: "村名字不能为空", trigger: "blur" }
        ],
        domicileNumber: [
          { required: true, message: "户籍号不能为空", trigger: "blur" }
        ],
        domicileLabel: [
          { required: true, message: "户标签不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getSenatorList();
    this.updateDomicileLabelsOnLoad();
  },
  methods: {
    // 根据村民ID获取村民的姓名，如果ID为空或未找到，不返回任何内容
    getVillagerName(villagerId) {
      if (!villagerId) return ''; // 直接返回空字符串，不显示“未知”
      const villager = this.villagersList.find(v => v.villagerId === villagerId);
      return villager ? villager.villagerName : '';
    },
    /** 查询网点机构列表 */
    getSenatorList() {
      listSenator({pageSize:10000000}).then(response => {
        this.senatorList = response.rows;

      });
    },
    getSenatorName(senatorId) {
      if (!senatorId) return ''; // 直接返回空字符串，不显示“未知”
      const Senator = this.senatorList.find(v => v.reviewerId=== senatorId);
      return Senator ? Senator.reviewerName : '';
    },
    // 生成悬浮框显示的评议员详细信息，如果ID为空或未找到对应信息，返回“无信息”
    getSenatorTooltipContent(senatorId) {
      if (!senatorId) return '无信息'; // 如果ID为空，返回“无信息”
      const senator = this.senatorList.find(v => v.reviewerId === senatorId);
      if (!senator) return '无信息'; // 如果未找到村民，也返回“无信息”
      return `
     评议员编号：${senator.reviewerId}<br>
     姓名: ${senator.reviewerName}<br>
     身份证号: ${senator.reviewerNumber.substring(0, 6) + '********' + senator.reviewerNumber.substring(14)}<br>
     手机号: ${senator.reviewerPhonenumber}<br>
     居住地址: ${senator.reviewerAddress}

   `;
    },
    // 生成悬浮框显示的村民详细信息，如果ID为空或未找到对应信息，返回“无信息”
    getVillagerTooltipContent(villagerId) {
      if (!villagerId) return '无信息'; // 如果ID为空，返回“无信息”
      const villager = this.villagersList.find(v => v.villagerId === villagerId);
      if (!villager) return '无信息'; // 如果未找到村民，也返回“无信息”
      return `
     村民编号: ${villager.villagerId}<br>
     姓名: ${villager.villagerName}<br>
     性别: ${villager.villagerSex}<br>
     年龄: ${villager.villagerAge}<br>
     与户主关系: ${villager.relationship}<br>
     身份证号: ${villager.villagerNumber.substring(0, 6) + '********' + villager.villagerNumber.substring(14)}<br>
     手机号: ${villager.villagerPhonenumber}<br>
     居住地址: ${villager.villagerAddress}<br>
     信息备注: ${villager.villagerNotes}
   `;
    },

    /** 查询评议情况列表 */
    getList() {
      if (this.isQuerySet) {
        this.loading = true;
        listDomicile(this.queryParams).then(response => {
          this.domicileList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }
    },

    // 新的方法用于在页面加载时更新户籍标签
    async updateDomicileLabelsOnLoad() {
      try {
        this.loading = true;

        // 加载所有户籍信息
        const domicileResponse = await listDomicile({pageSize: 100000000});
        this.domicileList = domicileResponse.rows;

        const villageResponse = await listVillage({pageSize: 1000000});
        this.villageList =villageResponse.rows;

        // 加载所有村民信息
        const villagersResponse = await listVillagers({pageSize: 100000000});
        this.villagersList = villagersResponse.rows;
        console.log("xxx",this.villagersList);
        // 执行更新逻辑
        await this.updateDomicileLabels();
        this.getList();
        this.loading = false;
      } catch (error) {
        console.error('Error updating domicile labels on load:', error);
        this.loading = false;
      }
    },
    // 抽离更新户籍标签的逻辑到一个独立的方法
    async updateDomicileLabels() {
      for (let domicile of this.domicileList) {
        const relatedVillagers = this.villagersList.filter(villager => villager.villagerDomicileNumber === domicile.domicileNumber);
        const allOutsideAgeRange = relatedVillagers.every(villager => villager.villagerAge < 22 || villager.villagerAge > 59);

        if (allOutsideAgeRange && relatedVillagers.length > 0) {
          try {
            await updateDomicile({
              domicileId: domicile.domicileId,
              domicileLabel: '2'
            });
            console.log(`Domicile ${domicile.domicileNumber} label updated to 2`);
          } catch (error) {
            console.error(`Failed to update domicile label for ${domicile.domicileNumber}:`, error);
          }
        } else {

          try {

            const response = await getVillage(domicile.villageId);
            const villageroundnumber = response.data.roundNumber;

            let money = 0;

            // 根据roundNumber计算money
            switch (villageroundnumber) {
              case "0":
                if(domicile.whiteMoney>0){money=parseFloat(domicile.whiteMoney);break;}
                if (domicile.oneSenatorId && domicile.twoSenatorId && domicile.domicileQualitySenatorId) {
                  money = (parseFloat(domicile.oneMoney) + parseFloat(domicile.twoMoney)) / 2;
                }
                break;
              case "1":
                if(domicile.whiteMoney>0){money=parseFloat(domicile.whiteMoney);break;}
                if (domicile.oneSenatorId && domicile.domicileQualitySenatorId) {
                  money = parseFloat(domicile.oneMoney);
                }
                break;
              case "2":
                if(domicile.whiteMoney>0){money=parseFloat(domicile.whiteMoney);break;}
                if (domicile.oneSenatorId) {
                  money = parseFloat(domicile.oneMoney);
                }
                break;
              default:
                break;
            }
            if(money>0 && domicile.domicileLabel == '2'){
              await updateDomicile({
                domicileId: domicile.domicileId,
                oneMoney: '0',
                oneSenatorId: '0',
                twoMoney: '0',
                twoSenatorId: '0',
                whiteSenatorId: '-1',
                whiteMoney: '-1',
                domicileQuality: 'N',
                domicileQualitySenatorId: '0',
                money: '0'
              });
            }
            // 根据money的值进行条件判断并更新
            if (money > 0 && domicile.domicileLabel !='2') {
              await updateDomicile({
                domicileId: domicile.domicileId,
                domicileLabel: '1',
                money: money
              });
            }
          } catch (error) {
            console.error(`Error processing domicile ID: ${domicile.domicileId}`, error);
          }
        }
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        domicileId: null,
        villageId: null,
        villageDomicileId: null,
        domicileNumber: null,
        domicileLabel: null,
        domicileVillagerId: null,
        oneMoney: null,
        oneSenatorId: null,
        twoMoney: null,
        twoSenatorId: null,
        whiteMoney:null,
        whiteSenatorId:null,
        domicileQuality: null,
        domicileQualitySenatorId: null,
        money: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // 判断是否设置了至少一个搜索条件
      this.isQuerySet = this.queryParams['bankVillage.villageName'] ||
        this.queryParams.domicileLabel ||
        this.queryParams.domicileVillagerId;
      if (this.isQuerySet) {
        this.queryParams.pageNum = 1;
        this.getList();
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 只清空户标签和主信贷人村民编号
      this.resetForm("queryForm");

      // 执行查询，以显示当前选定行政村的数据
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.domicileId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加评议情况";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const domicileId = row.domicileId || this.ids
      getDomicile(domicileId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改评议情况";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.domicileId != null) {
            updateDomicile(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDomicile(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const domicileIds = row.domicileId || this.ids;
      this.$modal.confirm('是否确认删除评议情况编号为"' + domicileIds + '"的数据项？').then(function() {
        return delDomicile(domicileIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bank/domicile/export', {
        ...this.queryParams
      }, `domicile_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
